import { useEffect } from 'react';

import { Button, Form, Input, InputNumber, Modal, Radio, Upload, UploadFile } from 'antd';
import { useModel } from '@umijs/max'
import {  editAdv } from './services';
import { useRequest } from 'ahooks';
import { SUCCESS_CODE } from '@/constants';
import { PlusOutlined } from '@ant-design/icons';
import { RcFile } from 'antd/es/upload';

const ModalImgConfig = {
  width: 1200, height: 1200, size: 2,
}
let fromType = 1;
const HandRefundPage: React.FC<RoutePageProps> = (props) => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editAdv, {manual: true})
  const { closeCurrentTab } = useModel('global')

  const onFinish = (formValues: any) => {
    runAsync({
      userId: formValues.id,
      reason: formValues.reason,
      money: formValues.money,
      other: formValues.other ? formValues.other[0].url : null,
    })
    .then(() => {
      if (Number(fromType) === 2) {
        console.info('defrr来源信息：', fromType)
        const event = new CustomEvent('refreshAppUserList')
        window.dispatchEvent(event)
        closeCurrentTab('/normal/normalList')
      } else {
        const event = new CustomEvent('refreshAppUserDetail')
        window.dispatchEvent(event)
        closeCurrentTab('/normal/normalList/detail?userId=' + formValues.id)
      }
    })
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  }

  const beforeUpload = async (file: RcFile) => {
    return Promise.resolve()
    if (file.size > 1024 * 1024 * ModalImgConfig.size) {
      Modal.warn({
        title: '提示',
        content: `请选择体积小于 ${ModalImgConfig.size}M 的图片`
      })
      return Upload.LIST_IGNORE
    }
    const reader = new FileReader()
    reader.readAsDataURL(file)
    const base64 = await new Promise((resolve) => {
      reader.onload = () => {
        resolve(reader.result)
      }
    })
    const img = new Image()
    img.src = base64 as string

    return Promise.resolve()
  }

  const onFileUpLoadChange = (file: UploadFile) => {
    const { status, response } = file
    if (status === 'done' && response) {
      const { code, data, text } = response
      if (code === SUCCESS_CODE) {
        editForm.setFieldsValue({
          other: [{status: 'done', url: data}]
        })
      } else {
        Modal.error({
          title: '错误',
          content: text === '上传文件过大' ? '文件体积超过 2M，请重新上传' : '图片上传失败，请重试',
        })
        editForm.setFieldsValue({
          other: []
        })
      }
    }
  }

  const onValuesChange = (values: any) => {

  }

  useEffect(() => {
    if (props.params.type === 'add') {
      fromType = props.params.from;
      editForm.setFieldsValue({
        id: props.params.id,
        reason: undefined,
        money: undefined,
        other: undefined,
      })
    } else {
    }
  }, [props.params.type])

  useEffect(() => {
    fromType = props.params.from
    console.info('来源信息：', fromType)
  }, [props.params.from])
  
  return (
    <div className='container'>
      <div className="card">
        <Form form={editForm} name='editForm' labelCol={{flex: '120px'}} onFinish={onFinish} onValuesChange={onValuesChange}>
          <Form.Item name='id' noStyle>
            <Input hidden />
          </Form.Item>


          <Form.Item name='money' label='退款金额' rules={[{required: true, message: '请输入退款金额'}]}>
            <InputNumber placeholder='请输入' style={{width: 320}} min={0} precision={2} />
          </Form.Item>
          <Form.Item name='reason' label='退款理由' rules={[{required: true, message: '请输入退款理由'}]}>
            <Input placeholder='请输入' style={{width: 320}} />
          </Form.Item>
          <Form.Item label="图片">
            <Form.Item
              name='other' rules={[{required: false, message: '请上传图片'}]}
              valuePropName="fileList" getValueFromEvent={normFile} noStyle
            >
              <Upload 
                action="/app/user/fileUp" listType="picture-card"
                data={{type: 1}} maxCount={1}
                headers={{Authorization: localStorage.Authorization}}
                beforeUpload={beforeUpload}
                onChange={({file}) => onFileUpLoadChange(file)}
                accept='.jpg, .png'
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>选择照片</div>
                </button>
              </Upload>
            </Form.Item>
            <div>
              提示：
              图片请上传 {ModalImgConfig.width} * {ModalImgConfig.height} 尺寸，体积小于 {ModalImgConfig.size}M 的图片
            </div>
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <Button type='primary' htmlType='submit' loading={loading}>提交</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default HandRefundPage;
